/*
 *
 * =========================================================================
 *
 * Copyright (c) 2009-2010 Sperasoft, Inc. All rights reserved.
 * This software is the confidential and proprietary information of Sperasoft, Inc.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of license agreement you entered into with Sperasoft, Inc.
 *
 * =========================================================================
 *
 * For more information, please see http://sperasoft.com
 *
 */
package org.shagin.jfin.core;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * The Class ResourceLocator.
 */
public class ResourceLocator {

	/** The Constant log. */
	private static final Logger log = LoggerFactory.getLogger(ResourceLocator.class);

	/**
	 * Find resource.
	 * 
	 * @param resourceName
	 *            the resource name
	 * 
	 * @return the uRL
	 * 
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	public static URL findResource(String resourceName) throws IOException {
		Debug.traceEnter(log, resourceName);
		URL result = null;
		Enumeration<URL> resources = Thread.currentThread()
				.getContextClassLoader().getResources(resourceName);
		if (resources.hasMoreElements())
			result = resources.nextElement();

		return result;
	}

	/**
	 * Gets the resource.
	 * 
	 * @param resourceName
	 *            the resource name
	 * 
	 * @return the resource
	 */
	public static URL getResource(String resourceName) {
		URL result;
		try {
			result = findResource(resourceName);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		if (null == result)
			throw new RuntimeException("Resource '" + resourceName
					+ " not found");
		return result;
	}

	/**
	 * Gets the resource input stream.
	 * 
	 * @param resourceName
	 *            the resource name
	 * 
	 * @return the resource input stream
	 */
	public static InputStream getResourceInputStream(String resourceName) {
		Debug.traceEnter(log, resourceName);
		InputStream stream = null;
		try {
			stream = new FileInputStream(getResource(resourceName).getPath());
		} catch (FileNotFoundException e) {
			throw new RuntimeException(e);
		}
		return stream;
	}
}
